package cn.hebutrun.oulabot.common.util;

import cn.hebutrun.oulabot.common.Constants;
import cn.hutool.core.util.CharUtil;
import cn.hutool.crypto.digest.BCrypt;
import lombok.experimental.UtilityClass;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 字符串处理工具
 *
 * @author zhaolong
 */
@UtilityClass
public class StringUtil {
  /**
   * 异常信息转换为字符串
   *
   * @param stackTraceElements 异常数组
   * @return 拼接信息
   */
  public String exceptionPrint(StackTraceElement[] stackTraceElements) {
    List<String> stackList = new ArrayList<>();
    for (StackTraceElement stackTraceElement : stackTraceElements) {
      stackList.add(stackTraceElement.toString());
    }
    return String.join("\n", stackList);
  }

  /**
   * MD5加密
   *
   * @param str 原字符串
   * @return 加密结果
   * @date 2022/3/9
   * @author zhaolong
   */
  public String MD5encrypt(String str) {
    return DigestUtils.md5DigestAsHex(str.getBytes());
  }

  /**
   * 字符串逢大写转为下划线小写 <br>
   * 不按照常规驼峰处理
   *
   * @param str 原字符串
   */
  public String toDBUnderlineCase(CharSequence str) {
    return toSymbolCase(str, CharUtil.UNDERLINE);
  }

  public String toSymbolCase(CharSequence str, char symbol) {
    if (str == null) {
      return null;
    }

    final int length = str.length();
    final StringBuilder sb = new StringBuilder();
    char c;
    for (int i = 0; i < length; i++) {
      c = str.charAt(i);
      if (Character.isUpperCase(c)) {
        sb.append(symbol);
        sb.append(Character.toLowerCase(c));
      } else {
        // 小写或符号
        sb.append(c);
      }
    }
    return sb.toString();
  }

  public String trimSeparator(String str) {
    String separator = Constants.SEPARATOR;
    while (str.contains(separator + separator)) {
      str = str.replaceAll(separator + separator, separator);
    }
    return str;
  }

  public String checkSeparator(String str) {
    str = trimSeparator(checkTailSeparator(checkHeadSeparator(str)));
    return str;
  }

  private String checkTailSeparator(String str) {
    if (!(Constants.SEPARATOR_CHAR == str.charAt(str.length() - 1))) {
      str += Constants.SEPARATOR_CHAR;
    }
    return str;
  }

  public String checkHeadSeparator(String str) {
    if (!(Constants.SEPARATOR_CHAR == str.charAt(0))) {
      str = Constants.SEPARATOR + str;
    }
    return str;
  }

  public String deleteTailSeparator(String str) {
    while (Constants.SEPARATOR_CHAR == str.charAt(str.length() - 1)) {
      str = str.substring(0, str.length() - 1);
    }
    return str;
  }

  public String checkUrl(String url) {
    return StringUtil.deleteTailSeparator(StringUtil.checkSeparator(url));
  }

  public String BcryptEncoder(String str) {
    return "{" + Constants.BCRYPT_PASSWORD_ENCODER_PREFIX + "}" + BCrypt.hashpw(str);
  }
}
